package cn.sail.shop3.api.dao.impl;

import cn.sail.shop3.api.dao.GoodsDao;
import cn.sail.shop3.api.entity.Goods;
import cn.sail.shop3.api.util.DBUtil;
import org.apache.commons.dbutils.*;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class GoodsDaoImpl implements GoodsDao {

    private QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());
    //开启驼峰转换
    BeanProcessor bean = new GenerousBeanProcessor();
    RowProcessor processor = new BasicRowProcessor(bean);

    @Override
    public void insert(Goods goods) {
        //定义sql
        String sql = "INSERT INTO `goods`( `goods_code`, `remark`, `img_url`, `price`,  `type_id`) VALUES (?, ?, ?, ?, ?)";
        //填充参数
        Object[] params = {goods.getGoodsCode(), goods.getRemark(), goods.getImgUrl(), goods.getPrice(), goods.getTypeId()};
        //执行sql
        try {
            int result = queryRunner.execute(sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void update(Goods goods) {

    }

    @Override
    public void delete(Long id) {

    }

    @Override
    public Goods selectById(Long id) {
        String sql = "SELECT * FROM goods WHERE id=?";
        Object[] params = {id};

        //执行SQL，填充参数，转换结果
        BeanHandler<Goods> beanHandler = new BeanHandler(Goods.class, processor);

        try {
            Goods goods = queryRunner.query(sql, beanHandler, params);
            return goods;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<Goods> selectListByTypeId(Long typeId) {
        String sql = "SELECT * FROM goods WHERE type_id=?";
        Object[] params = {typeId};

        //执行SQL，填充参数，转换结果
        BeanListHandler<Goods> beanHandler = new BeanListHandler(Goods.class, processor);

        try {
            List<Goods> goodsList = queryRunner.query(sql, beanHandler, params);
            return goodsList;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<Goods> selectList() {
        String sql = "SELECT * FROM goods";

        //执行SQL，填充参数，转换结果
        BeanListHandler<Goods> beanHandler = new BeanListHandler(Goods.class, processor);

        try {
            List<Goods> goodsList = queryRunner.query(sql, beanHandler);
            System.out.println(goodsList);
            return goodsList;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
}
